package com.jushu.storbox;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.adapter.ShareUplodAdapter;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.network.WifiController;
import com.jushu.storbox.service.CloudDriveService;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.util.ApplicationContext;
import com.jushu.storbox.util.DataUploadUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.util.image.BitmapUtil;
import com.jushu.storbox.util.image.IconVerification;
import com.jushu.storbox.view.dialog.ExceptionPrompt;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;

public class ShareActivity extends Activity {
	private static final String LOG_TAG = "ShareActivity";

	private ImageView fileIcon;

	private RelativeLayout spinnerButton;

	private RelativeLayout shareBack, getfolderListProgressBar,
			folderListLayout;

	private TextView fileAdrrss, folder_name, spinnerText;

	// public MyPopupWindow popWindow;
	private View shareView;

	private String sharePath;

	private int uploadType = 0;

	private Button confirm_btn, canccle_btn, shareButtonUplod, shareCancel;

	private LayoutInflater layoutInflater;

	private ListView fileList_lv;

	private ICloudDriveService shareDriveService;

	private List<FileFolderInfo> moveList = null;

	private List<List<FileFolderInfo>> shareFileList = null;

	private List<String> fileFolderList = null;

	private int shareFileListID = 0;

	private String shareFileListName;

	private String fileID = "0";

	private InputStream inputStream = null;

	private String shareFileurl;

	private List<String> shareFileListUrl = new ArrayList<String>();;

	private File shareFile = null;

	private RelativeLayout shareViewLayout;

	private ProgressBar loginProgressbar;

	// private PopupWindow pwPopupWindow;
	private iFileManager mdmTools = null;

	private boolean isSelect = true;

	private ShareUplodAdapter adapter = null;

	private TextView mShareFileSizeTextView;

	private View mParentLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.share_layout);
//		ActivityTaskManager.getInstance().putActivity(LOG_TAG, ShareActivity.this);
		initView();
		setViewClickListener();
		getIntentDataFromIntent();
		initBindService();
	}

	private void initBindService() {
		// TODO Auto-generated method stub
		Intent bindIntent = new Intent(ShareActivity.this,
				CloudDriveService.class);
		if (null != serviceConnection) {
			LogUtil.i(LOG_TAG, "Bind CloudDriveService...");
			bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
		}
	}

	private void addAnim() {
		Animation anim = new AlphaAnimation(0, 1);
		anim.setFillAfter(true);
		anim.setDuration(500);
		anim.setRepeatCount(1);
		mParentLayout.setAnimation(anim);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	private ServiceConnection serviceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			LogUtil.i(LOG_TAG, "onServiceConnected start...");
			shareDriveService = ((CloudDriveService.CenterShareDriveServiceServiceBinder) service)
					.getService();
			checkNetWorkAutoLogin();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			LogUtil.e(LOG_TAG, "onServiceDisconnected...");
		}
	};

	private boolean shareWithoutLogin = false;

	private void checkNetWorkAutoLogin() {
		if (shareWithoutLogin) {
			return;
		}

		if (null != shareDriveService) {
			int struts = new WifiController(ShareActivity.this).getNetWord();
			if (struts == 0)
			{
				LogUtil.e(
						LOG_TAG,
						"onServiceConnected, "
								+ ShareActivity.this.getResources().getString(
										R.string.allfile_notwork_obstructed));
				Toast.makeText(
						ShareActivity.this,
						ShareActivity.this.getResources().getString(
								R.string.allfile_notwork_obstructed),
						Toast.LENGTH_LONG).show();
				ShareActivity.this.finish();
			} else {
				LogUtil.i(LOG_TAG,
						"onServiceConnected, network enable that execute AsyloginVerification...");
				new AsyloginVerification().execute();
			}
		} else {
			LogUtil.e(LOG_TAG,
					"serviceConnected fail, shareDriveService is null...");
		}
	}

	private class AsyloginVerification extends
			AsyncTask<Integer, Integer, Integer> {
		Handler verifyHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					loginProgressbar.setVisibility(View.GONE);
					shareViewLayout.setVisibility(View.VISIBLE);
					break;
				default:
					loginProgressbar.setVisibility(View.GONE);
					ExceptionPrompt.showException(msg.what, ShareActivity.this);
					break;
				}
				super.handleMessage(msg);
			}
		};

		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (null != shareDriveService) {
				LogUtil.i(LOG_TAG,
						"AsyloginVerification loginBackGround start...");
				shareDriveService.loginBackGround(verifyHandler);
			} else {
				LogUtil.e(LOG_TAG,
						"AsyloginVerification loginBackGround fail, shareDriveService is null...");
			}
			return null;
		}
	}

	private void initView() {
		layoutInflater = getLayoutInflater();
		fileIcon = (ImageView) findViewById(R.id.share_layout_image);
		fileAdrrss = (TextView) findViewById(R.id.share_layout_text);
		shareViewLayout = (RelativeLayout) findViewById(R.id.share_view_layout_id);
		shareButtonUplod = (Button) findViewById(R.id.share_button_uplod);
		shareCancel = (Button) findViewById(R.id.share_cancel);
		loginProgressbar = (ProgressBar) findViewById(R.id.share_file_progressBar);
		shareView = layoutInflater.inflate(
				R.layout.share_file_folder_window_layout, null);
		getfolderListProgressBar = (RelativeLayout) shareView
				.findViewById(R.id.share_getfolder_list_progressBar_layout);
		folderListLayout = (RelativeLayout) shareView
				.findViewById(R.id.share_folder_list_layout);
		spinnerText = (TextView) findViewById(R.id.share_spinner_text);
		spinnerButton = (RelativeLayout) findViewById(R.id.share_spinner_button);
		canccle_btn = (Button) shareView.findViewById(R.id.canccle_btn);
		confirm_btn = (Button) shareView.findViewById(R.id.confirm_btn);
		fileList_lv = (ListView) shareView.findViewById(R.id.FileList_lv);
		shareBack = (RelativeLayout) shareView
				.findViewById(R.id.share_file_folder_list_top_re);
		folder_name = (TextView) shareView
				.findViewById(R.id.list_folder_name_tv);
		shareFileList = new ArrayList<List<FileFolderInfo>>();
		fileFolderList = new ArrayList<String>();
		mShareFileSizeTextView = (TextView) findViewById(R.id.tv_share_file_size);
		mParentLayout = findViewById(R.id.layout_parent);
		setViewTextData();
	}

	private void setViewTextData() {
		fileIcon.setBackgroundResource(R.mipmap.default_file_icon);
		folder_name.setText(ShareActivity.this.getResources().getString(
				R.string.share));
		spinnerText.setText(ShareActivity.this.getResources().getString(
				R.string.my_cloud_drive));
	}

	private Intent smartInitIntent() {

		Intent retIntent = null;

		if (null == ShareDriveApplication.getInstance().getAuthorization()
				|| PublicTools.isAuthiorzationGotoTimeout(this)) {
			if(!ApplicationContext.getInstance().isRedirectLoginSuccess()){
				Toast.makeText(
						this,
						getResources().getString(
								R.string.share_failed),
						Toast.LENGTH_LONG).show();
				return null;
			}
			Constant.setShareWithoutLogin(this, true);
			ShareDriveApplication.getInstance().setShareNotFinishIntent(
					getIntent());

			LogUtil.e("~~", "aaaa");
			Intent loginIntent = new Intent(this, LoginActivity.class);
			loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			if(PublicTools.isLoginSuccess(ShareActivity.this)){
				Toast.makeText(
						this,
						getResources().getString(
								R.string.please_login_stor_box_disk),
						Toast.LENGTH_LONG).show();
			}

			startActivity(loginIntent);
			shareWithoutLogin = true;
			this.finish();
			return null;

		} else if (Constant.getShareWithoutLogin(this)) {
			Constant.setShareWithoutLogin(this, false);
			retIntent = ShareDriveApplication.getInstance()
					.getShareNotFinishIntent();
			if (retIntent == null) {
				// Toast.makeText(this, R.string.share_file_fail_need_retry,
				// Toast.LENGTH_SHORT).show();
				this.finish();
				return null;
			}

		} else {
			retIntent = getIntent();
		}

		return retIntent;

	}

	private void getIntentDataFromIntent() {
		final Intent intent = smartInitIntent();
		if (intent == null) {
			return;
		}

		final Bundle extras = intent.getExtras();
		Log.e("~~", "setdata");
		if (extras.getString("uploadFileUrl") != null
				&& !extras.getString("uploadFileUrl").equals("")) {
			shareFileurl = extras.getString("uploadFileUrl");
			otherModularShare(extras);
			uploadType = 1;
		} else if (intent.getType().equals("huaweiapp/*")) {
			shareFileurl = extras.getString("fileEnPath");
			thirdPartySoftwareShare(extras);
			uploadType = 2;
		} else {
			localFileShare(intent);
			uploadType = 0;
		}

		//
		if (shareFileurl == null || shareFileurl.equals("")) {
			Log.e("~~", " shareFileurl == null");
			//
			Message msg = new Message();
			msg.what = 9;
			handler.sendMessage(msg);
			ShareActivity.this.finish();
			return;
		}
	}

	private void otherModularShare(Bundle extras) {
		shareFile = new File(extras.getString("uploadFileUrl"));
		shareFileurl = shareFile.getPath();
		//
		Bitmap bmp = null;
		int ivResID = -2;
		String name = "";
		String size = "";
		//
		if (shareFile.exists() && shareFile.length() > 0) {
			ivResID = IconVerification.getTypeImgeID(shareFile.getName());
			if (-1 == ivResID) {
				bmp = BitmapUtil.createImageThumbnail(
						shareFile.getAbsolutePath(),
						PublicTools.getWindowWidth(ShareActivity.this),
						PublicTools.getWindowHeight(ShareActivity.this));
			}
			name = shareFile.getName();
			size = PublicTools.changeBKM("" + shareFile.length());
			// IconVerification.fileIcon(ShareActivity.this,fileIcon,
			// shareFileurl, shareFile.getName());
			// fileAdrrss.setText(shareFile.getName());
			// mShareFileSizeTextView.setText(PublicTools.calculateSizeOfFile(shareFile));
		} else {
			Message msg = new Message();
			msg.what = 10;
			handler.sendMessage(msg);
			ShareActivity.this.finish();
			// Toast.makeText(getApplicationContext(),
			// getApplicationContext().getResources().getString(R.string.filebrowser_smaller_than_zero),
			// Toast.LENGTH_LONG).show();
			// ShareActivity.this.finish();
		}
		//
		Message msg = new Message();
		msg.what = 6;
		msg.obj = bmp;// bmp
		msg.arg1 = ivResID;// iv res id
		msg.setData(extras);
		extras.putString("name", name);
		extras.putString("size", size);
		handler.sendMessage(msg);
	}

	private void thirdPartySoftwareShare(final Bundle extras) {
		// TODO Auto-generated method stub
		String uName = PublicTools.checkUserNameFormat(extras
				.getString("userName"));
		String fEncDir = extras.getString("fileEncDir");
		String pName = extras.getString("pkgName");
		String fEnPath = extras.getString("fileEnPath");
		Log.e("~~", "fEnPath:" + fEnPath);
		if (fEnPath != null && !fEnPath.equals("") && fEncDir != null
				&& !fEncDir.equals("") && pName != null && !pName.equals("")
				&& uName != null && !uName.equals("")) {
			if (PublicTools.getClientUserName(ShareActivity.this) == null
					|| PublicTools.getClientUserName(ShareActivity.this).trim()
							.equals("")) {
				ShareActivity.this.finish();
				return;
			}
			if (!PublicTools.getClientUserName(ShareActivity.this)
					.equals(uName)) {
				handler1.sendEmptyMessage(7);
				ShareActivity.this.finish();
				return;
			}
			Log.e("~~", "fEncDir:" + fEncDir);
			getBitmap(uName, fEncDir, fEnPath);
		}
	}

	private void getBitmap(String uName, String fEncDir, String fEnPath) {
		File file = new File(fEnPath);
		shareFileurl = fEnPath;
		try {
			inputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			if (!file.exists()) {
				Message msg = new Message();
				msg.what = 11;
				handler.sendMessage(msg);
			} else {
				Message msg = new Message();
				msg.what = 10;
				handler.sendMessage(msg);
			}
			ShareActivity.this.finish();
		}

		if (file.length() > 0) {
			int ivResID = IconVerification.getTypeImgeID(file.getName());
			Bitmap bmp = null;
			if (-1 == ivResID) {
				bmp = BitmapUtil.createImageThumbnail(file.getAbsolutePath(),
						PublicTools.getWindowWidth(ShareActivity.this),
						PublicTools.getWindowHeight(ShareActivity.this));
			}

			Message msg = new Message();
			msg.what = 6;
			msg.obj = bmp;// bmp
			msg.arg1 = ivResID;// iv res id
			Bundle b = new Bundle();
			b.putString("name", file.getName());
			b.putString("size", PublicTools.changeBKM("" + file.length()));
			msg.setData(b);
			handler.sendMessage(msg);
		} else {
			Message msg = new Message();
			msg.what = 10;
			handler.sendMessage(msg);
		}
		ShareActivity.this.finish();
	}

	private void cleanTempData(final String tmpDataPath,
			final String tmpOneBoxPath) {
		//
		File tmpFolder = new File(tmpDataPath);
		if (!tmpFolder.exists()) {
			LogUtil.i(LOG_TAG, "tmpFolder is no exists, need mkdirs");
			tmpFolder.mkdirs();
		} else {
			LogUtil.i(LOG_TAG, "tmpFolder is exists, need deleteFileCache");
			if (needCleanTempData()) {
				LogUtil.i(LOG_TAG,
						"clean temp data has reach time, need deleteFileCache");
				try {
					new Thread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							PublicTools.deleteFileCache(tmpDataPath);
							PublicTools.deleteFileCache(tmpOneBoxPath);
						}
					}).start();
				} catch (Exception e) {
					// TODO: handle exception
				}
			} else {
				LogUtil.i(LOG_TAG,
						"clean temp data has no reach time,no need deleteFileCache");
			}
		}
	}

	private boolean needCleanTempData() {
		boolean isClean = false;
		long nowTime = System.currentTimeMillis();
		try {
			long cleanTempTime = PublicTools
					.getCleanTempTime(ShareActivity.this);
			if (ClientConfig.CLEAN_TIME < nowTime - cleanTempTime) {
				LogUtil.i(LOG_TAG, "needCleanTempData need clean... nowTime:"
						+ nowTime + " | cleanTempTime:" + cleanTempTime);
				PublicTools.setCleanTempTime(ShareActivity.this, nowTime);
				isClean = true;
			} else {
				LogUtil.i(LOG_TAG,
						"needCleanTempData no need clean... nowTime:" + nowTime
								+ " | cleanTempTime:" + cleanTempTime);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			isClean = false;
			LogUtil.e(LOG_TAG, "needCleanTempData Exception no need clean..."
					+ e.getLocalizedMessage());
		}
		return isClean;
	}

	private void localFileShare(Intent intent) {
		String action = intent.getAction();
		Bundle extras = intent.getExtras();
		String type = intent.getType();
		//
		Bitmap bmp = null;
		int ivResID = -2;
		String name = "";
		String size = "";

		//
		if (Intent.ACTION_SEND.equals(action) && type != null) {
			Uri uri = (Uri) intent.getExtras().getParcelable(
					Intent.EXTRA_STREAM);
			if (uri == null) {
				shareFileurl = null;
			} else {
				String filePath = handleSingleData(intent, uri);
				shareFileurl = filePath;
				shareFileListUrl.add(shareFileurl);
			}

		} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
			ArrayList<Parcelable> uris = intent
					.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
			if (uris == null || uris.isEmpty()) {
				shareFileurl = null;
			} else {
				List<String> filePathList = handleMultipleData(intent, uris);
				if (!filePathList.isEmpty()) {
					shareFileurl = filePathList.get(0);
					shareFileListUrl = filePathList;
				}
			}
		} else {
			LogUtil.d("Handle other intents");
			// Handle other intents, such as being started from the home screen
		}
		if (shareFileurl != null && !shareFileurl.equals("")) {
			shareFile = new File(shareFileurl);
			if (shareFile.exists() && shareFile.length() > 0) {
				ivResID = IconVerification.getTypeImgeID(shareFile.getName());
				if (-1 == ivResID) {
					bmp = BitmapUtil.createImageThumbnail(
							shareFile.getAbsolutePath(),
							PublicTools.getWindowWidth(ShareActivity.this),
							PublicTools.getWindowHeight(ShareActivity.this));
				}
				name = shareFile.getName();
				size = PublicTools.changeBKM("" + shareFile.length());
			} else {
				Message msg = new Message();
				msg.what = 10;
				handler.sendMessage(msg);
				ShareActivity.this.finish();
			}
		} else {
			Message msg = new Message();
			msg.what = 9;
			handler.sendMessage(msg);
			ShareActivity.this.finish();
		}
		//
		Message msg = new Message();
		msg.what = 6;
		msg.obj = bmp;// bmp
		msg.arg1 = ivResID;// iv res id
		msg.setData(extras);
		extras.putString("name", name);
		extras.putString("size", size);
		handler.sendMessage(msg);
	}

	private List<String> handleMultipleData(Intent intent,
			ArrayList<Parcelable> Uris) {
		List<String> multiplePath = new ArrayList<String>();
		String filePath = "";
		for (Parcelable pa : Uris) {
			Uri uri = (Uri) pa;
			String scheme = uri.getScheme();
			if (scheme.equals("content")) {
				ContentResolver cr = getContentResolver();
				Cursor c = cr.query(uri, null, null, null, null);
				c.moveToFirst();
				filePath = c.getString(c
						.getColumnIndexOrThrow(Images.Media.DATA));
				c.close();
				LogUtil.d("filePath = " + filePath);
				multiplePath.add(filePath);
			} else if (scheme.equals("file")) {
				filePath = uri.getPath();
				LogUtil.d("filePath = " + filePath);
				multiplePath.add(filePath);
			}
		}
		return multiplePath;
	}

	private String handleSingleData(Intent intent, Uri uri) {
		String filePath = "";
		String scheme = uri.getScheme();
		if (scheme.equals("content")) {
			ContentResolver cr = getContentResolver();
			Cursor c = cr.query(uri, null, null, null, null);
			c.moveToFirst();
			filePath = c.getString(c.getColumnIndexOrThrow(Images.Media.DATA));
			c.close();
			LogUtil.d("filePath = " + filePath);
		} else if (scheme.equals("file")) {
			filePath = uri.getPath();
			LogUtil.d("filePath = " + filePath);
		}
		return filePath;
	}

	private void setViewClickListener() {
		spinnerButton.setOnClickListener(new ButtonClickListener());
		shareBack.setOnClickListener(new ButtonClickListener());
		confirm_btn.setOnClickListener(new ButtonClickListener());
		canccle_btn.setOnClickListener(new ButtonClickListener());
		shareCancel.setOnClickListener(new ButtonClickListener());
		shareButtonUplod.setOnClickListener(new ButtonClickListener());
	}

	@SuppressWarnings("deprecation")
	private void showMoveWindow() {
		Intent intent = new Intent(ShareActivity.this,
				ShareSelectActivity.class);
		startActivityForResult(intent, 0);
		// startActivity(intent);
		// popWindow = new MyPopupWindow(ShareActivity.this);
		// pwPopupWindow =
		// popWindow.initPopupWindow(shareView,LayoutParams.MATCH_PARENT,
		// LayoutParams.FILL_PARENT);
		// pwPopupWindow.setOutsideTouchable(true);
		// pwPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// pwPopupWindow.showAtLocation(spinnerButton, Gravity.CENTER, 0, 0);
		// spinnerButton.setImageResource(R.drawable.share_select_go_b);
		// sharePath =
		// ShareActivity.this.getResources().getString(R.string.Root_directory);
		// pwPopupWindow.setOnDismissListener(new OnDismissListener() {
		// @Override
		// public void onDismiss() {
		// spinnerButton.setImageResource(R.drawable.share_select_go_a);
		// }
		// });
		// fileID = "0";
		// shareFileListName =
		// ShareActivity.this.getResources().getString(R.string.my_cloud_disk);
		// fileFolderList.add(ShareActivity.this.getResources().getString(R.string.share));
		// shareFileListID = 0;
		// getData("0");
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 1) {
			fileID = data.getStringExtra("fileParentID");
			shareFileListName = data.getStringExtra("fileParentName");
			LogUtil.i(LOG_TAG, "confirm.. fileID:" + fileID
					+ " | shareFileListName:" + shareFileListName);
			spinnerText.setText(shareFileListName);
		} else if (resultCode == 2) {
			LogUtil.i(LOG_TAG, "cancel..");
		} else {
			LogUtil.i(LOG_TAG, "back..");
		}
	}

	private void getData(final FileFolderInfo folder) {
		getfolderListProgressBar.setVisibility(View.VISIBLE);
		folderListLayout.setVisibility(View.GONE);
		new Thread(new Runnable() {
			public void run() {
				try {
					if (null != shareDriveService) {
						LogUtil.i(LOG_TAG, "ListView Get Data start...");
						moveList = shareDriveService.getMoveFolderList(
								folder.getOwnerId(), folder.getId(), "DESC", 1000, 0, "modifiedAt");
					} else {
						LogUtil.e(LOG_TAG,
								"ListView Get Data fail, shareDriveService is null...");
					}
					shareFileList.add(moveList);
					Message message = new Message();
					message.what = 1;
					handler.sendMessage(message);
				} catch (ClientException e) {
					Message message = new Message();
					message.what = 5;
					Bundle bundle = new Bundle();
					bundle.putInt("loadCode", e.getStatusCode());
					message.setData(bundle);
					handler.sendMessage(message);
				}
			}
		}).start();
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = null;
			switch (msg.what) {
			case 1:
				if (shareFileList.get(shareFileListID) != null) {
					adapter = new ShareUplodAdapter(ShareActivity.this,
							shareFileList.get(shareFileListID));
					fileList_lv.setAdapter(adapter);
					getfolderListProgressBar.setVisibility(View.GONE);
					folderListLayout.setVisibility(View.VISIBLE);
					isSelect = true;
					fileList_lv
							.setOnItemClickListener(new FileListItemClickListener());
				}
				break;
			case 3:
				bundle = (Bundle) msg.obj;
				Toast.makeText(
						ShareActivity.this,
						bundle.getString("uploadFilename")
								+ ShareActivity.this
										.getResources()
										.getString(
												R.string.fileListadapter_upload_success),
						Toast.LENGTH_SHORT).show();
				break;
			case 4:
				bundle = (Bundle) msg.obj;
				Toast.makeText(
						ShareActivity.this,
						bundle.getString("uploadFilename")
								+ ShareActivity.this.getResources().getString(
										R.string.fileListadapter_upload_failed),
						Toast.LENGTH_SHORT).show();
				break;
			case 5:
				bundle = (Bundle) msg.getData();
				ExceptionPrompt.showException(bundle.getInt("loadCode"),
						ShareActivity.this);
				// popWindow.closePopupWindow();
				shareFileList.clear();
				shareFileListID = 0;
				folder_name.setText(ShareActivity.this.getResources()
						.getString(R.string.share));
				// pwPopupWindow.dismiss();
				break;
			// refresh ui
			case 6:
				Bundle b = msg.getData();
				int ivResID = msg.arg1;
				if (-1 == ivResID) {
					Bitmap bmp = (Bitmap) msg.obj;
					fileIcon.setImageBitmap(bmp);
				} else if (-2 == ivResID) {
					fileIcon.setImageResource(R.mipmap.default_file_icon);
				} else {
					fileIcon.setImageResource(ivResID);
				}
				String name = b.getString("name");
				String size = b.getString("size");
				if (null != shareFileListUrl && 1 < shareFileListUrl.size()) {
					shareButtonUplod.setText(getString(R.string.nav_save_txt)
							+ "(" + shareFileListUrl.size() + ")");
				} else {
					shareButtonUplod.setText(getString(R.string.nav_save_txt));
				}
				fileAdrrss.setText(name);
				mShareFileSizeTextView.setText(size);
				break;
			// refresh ui
			case 9:
				//
				Bundle tmpBundle = getIntent().getExtras();
				Intent linkShareIntent = new Intent(ShareActivity.this, LinkFileSearchActivity.class);
				linkShareIntent.putExtras(tmpBundle);
				startActivity(linkShareIntent);
				break;
			case 10:
				//
				Toast.makeText(
						getApplicationContext(),
						getApplicationContext().getResources().getString(
								R.string.filebrowser_smaller_than_zero),
						Toast.LENGTH_LONG).show();
				break;
			case 11:
//				Toast.makeText(
//						getApplicationContext(),
//						getApplicationContext().getResources().getString(
//								R.string.filebrowser_path_no_exist),
//						Toast.LENGTH_LONG).show();
				break;
			}
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler handler1 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:

				break;
			case 3://file stream
				String fileUrl1 = String.valueOf(msg.obj);
				//
				if (null != fileUrl1 && !"".equals(fileUrl1)) {
					Bundle bundle1 = msg.getData();
					String folderID1 = bundle1.getString("folderID", "0");
					String fileId1 = bundle1.getString("fileID", "1");
					String filePath1 = bundle1.getString("filePath", "");
					String fileEncPath = bundle1.getString("fileEncPath", "");
					iFileManager mdmTools = null;
					boolean needDelete = false;
					if (null == fileEncPath || "".equals(fileEncPath)) {
						needDelete = true;
						mdmTools = FileManagerFactory
								.getFileManager(ShareActivity.this);
					} else {
						needDelete = false;
						mdmTools = FileManagerFactory.getFileManager(
								ShareActivity.this, fileEncPath);
					}
					FileInfoResponseV2 fileInfoResponse1 = mdmTools
							.getFileInfo(fileId1, folderID1, filePath1);

					if (null != fileInfoResponse1) {
						if (null != shareDriveService) {
							long result = shareDriveService
									.insertUploadData(fileInfoResponse1);
							if (-1 != result) {
								String ownerId = ShareDriveApplication.getInstance().getWnerID();
								DAOFactory.instance(ShareActivity.this)
										.getFolderDao()
										.setChangedFolderId(ownerId , folderID1, "1");
							}
						}
					}
					//
					if (needDelete) {
						boolean isDelete = mdmTools.deleteFile(fileUrl1);
					}
				}
				Toast.makeText(
						ShareActivity.this,
						ShareActivity.this.getResources().getString(
								R.string.fileListadapter_upload_success),
						Toast.LENGTH_SHORT).show();
				break;
			case 4:
				Toast.makeText(
						ShareActivity.this,
						ShareActivity.this.getResources().getString(
								R.string.fileListadapter_upload_failed),
						Toast.LENGTH_SHORT).show();
				break;
			case 5:// file not exist
				Toast.makeText(
						ShareActivity.this,
						ShareActivity.this.getResources().getString(
								R.string.fileListadapter_upload_failed)
								+ ","
								+ ShareActivity.this.getResources().getString(
										R.string.fileListadapter_file_notfond),
						Toast.LENGTH_LONG).show();
				break;
			case 6:// upload fail,file not exist or account not equal
//				Toast.makeText(
//						ShareActivity.this,
//						ShareActivity.this.getResources().getString(
//								R.string.fileListadapter_upload_failed)
//								+ ","
//								+ ShareActivity.this.getResources().getString(
//										R.string.fileListadapter_file_notfond)
//								+ "&"
//								+ ShareActivity.this.getResources().getString(
//										R.string.account_no_same),
//						Toast.LENGTH_LONG).show();
				break;
			case 7:// upload fail,account not equal
//				Toast.makeText(
//						ShareActivity.this,
//						ShareActivity.this.getResources().getString(
//								R.string.fileListadapter_upload_failed)
//								+ ","
//								+ ShareActivity.this.getResources().getString(
//										R.string.account_no_same),
//						Toast.LENGTH_LONG).show();
				break;
			case 1003:// file upload success
				// insert to database
				Bundle bundle2 = msg.getData();
				String folderID2 = bundle2.getString("folderID", "0");
				String fileId2 = bundle2.getString("fileID", "1");
				String filePath2 = bundle2.getString("filePath", "");
				String fileEncPath2 = bundle2.getString("fileEncPath", "");
				iFileManager mdmTools = null;

				if (null == fileEncPath2 || "".equals(fileEncPath2)) {
					mdmTools = FileManagerFactory
							.getFileManager(ShareActivity.this);

				} else {
					mdmTools = FileManagerFactory.getFileManager(
							ShareActivity.this, fileEncPath2);
				}

				FileInfoResponseV2 fileInfoResponse2 = mdmTools.getFileInfo(
						fileId2, folderID2, filePath2);

				if (null != fileInfoResponse2) {
					if (null != shareDriveService) {
						long result = shareDriveService
								.insertUploadData(fileInfoResponse2);
						if (-1 != result) {
							String ownerId = ShareDriveApplication.getInstance().getWnerID();
							DAOFactory.instance(ShareActivity.this)
									.getFolderDao()
									.setChangedFolderId(ownerId, folderID2, "1");
						}
					}
				}
				Toast.makeText(
						ShareActivity.this,
						ShareActivity.this.getResources().getString(
								R.string.fileListadapter_upload_success),
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		}
	};

	private class FileListItemClickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			if (isSelect) {
				getData(shareFileList.get(shareFileListID).get(arg2));
				fileID = shareFileList.get(shareFileListID).get(arg2).getId();
				folder_name.setText(shareFileList.get(shareFileListID)
						.get(arg2).getName());
				shareFileListName = shareFileList.get(shareFileListID)
						.get(arg2).getName();
				fileFolderList.add(shareFileListName);
				shareFileListID += 1;
				isSelect = false;
			}
		}
	}

	private class ButtonClickListener implements OnClickListener {
		@Override
		public void onClick(View arg0) {
			if (arg0.equals(spinnerButton)) {
				showMoveWindow();
			} else if (arg0.equals(shareBack)) {
				if (isSelect) {
					if (shareFileListID != 0) {
						if (shareFileList.size() > 0) {
							shareFileList.remove(shareFileList.size() - 1);
							fileFolderList.remove(fileFolderList.size() - 1);
							shareFileListID -= 1;
							if (fileFolderList.size() > 0) {
								folder_name.setText(fileFolderList
										.get(shareFileListID));
							} else if (shareFileListID == 0) {
								folder_name.setText(ShareActivity.this
										.getResources().getString(
												R.string.share));
							}
							adapter = new ShareUplodAdapter(ShareActivity.this,
									shareFileList.get(shareFileListID));
							fileList_lv.setAdapter(adapter);
							fileList_lv
									.setOnItemClickListener(new FileListItemClickListener());
						} else {

						}
					}
				}
			} else if (arg0.equals(confirm_btn)) {
				// popWindow.closePopupWindow();
				spinnerText.setText(shareFileListName);
				shareFileList.clear();
				folder_name.setText(ShareActivity.this.getResources()
						.getString(R.string.share));
				// pwPopupWindow.dismiss();
			} else if (arg0.equals(canccle_btn)) {
				// popWindow.closePopupWindow();
				shareFileList.clear();
				shareFileListID = 0;
				folder_name.setText(ShareActivity.this.getResources()
						.getString(R.string.share));
				// pwPopupWindow.dismiss();
			} else if (arg0.equals(shareButtonUplod)) {
				if (uploadType == 0) {
					for (String url : shareFileListUrl) {
						if (new File(url).length() > Constant.ONE_GB) {
							Toast.makeText(
									ShareActivity.this,
									ShareActivity.this
											.getString(R.string.filebrowser_bigger_than_1GB),
									Toast.LENGTH_SHORT).show();
							return;
						}
					}
				}

				DataUploadUtil dataUploadTools = new DataUploadUtil(
						getApplicationContext(), shareDriveService);
				if (uploadType == 0) {
					if (null != shareFileListUrl) {
						for (String url : shareFileListUrl) {
							dataUploadTools = new DataUploadUtil(
									getApplicationContext(), shareDriveService);
							dataUploadTools.uploadShareFile(fileID, url,
									handler1);
						}
					} else {
						Log.e(LOG_TAG, "Share fial , shareFileListUrl is Null ");
					}
					for (String url : shareFileListUrl) {
						dataUploadTools = new DataUploadUtil(
								getApplicationContext(), shareDriveService);
						dataUploadTools.uploadShareFile(fileID, url, handler1);
					}
					ShareActivity.this.finish();
				} else if (uploadType == 2) {
					dataUploadTools.uploadStream(fileID, shareFileurl,
							getIntent().getExtras().getString("fileEncDir"),
							inputStream, handler1);
					ShareActivity.this.finish();
				} else if (uploadType == 1) {
					dataUploadTools
							.uploadStream(fileID, shareFileurl, handler1);
				}
				// Intent shareIntent = new Intent(ShareActivity.this,
				// UploadService.class);
				// shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				// Bundle bundle = new Bundle();
				// bundle.putString("uploadFileUrl", shareFileurl);
				// bundle.putString("file_parent_directory_id", fileID);
				// shareIntent.putExtras(bundle);
				// ShareActivity.this.startService(shareIntent);
				ShareActivity.this.finish();
			} else if (arg0.equals(shareCancel)) {
				ShareActivity.this.finish();
			}
		}
	}

	/**
	 * @param act
	 * @param contentUri
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public String getRealPathFromURI(Activity act, Uri contentUri) {
		// can post image
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = null;
		try {
			if (null != act && null != contentUri) {
				cursor = act.managedQuery(contentUri, proj, null, null, null);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getRealPathFromURI managedQuery error..");
		}
		if (cursor != null) {
			if (cursor.getCount() > -1) {
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				return cursor.getString(column_index);
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// ActivityTaskManager.getInstance().removeActivity(LOG_TAG);
		if (null != serviceConnection) {
			LogUtil.i(LOG_TAG, "unBindService");
			unbindService(serviceConnection);
		}
	}
}
